package com.lcdpg.lcdp.auth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName SecurityConfig.java
 * @Description TODO
 * @createTime 2025年05月25日 14:25:00
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 配置密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置用户信息（加密密码）
    @Bean
    public UserDetailsService userDetailsService() {
        String encodedPassword = passwordEncoder().encode("dev");
        UserDetails user = User.builder()
                .username("dev")
                .password(encodedPassword)
                .roles("DEV")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    // 配置安全规则（修复点）
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http

                .csrf(AbstractHttpConfigurer::disable) // 关闭 CSRF 防护（关键）
                .cors(withDefaults())
                .authorizeHttpRequests(auth -> auth
                        // 放行 Swagger 相关资源路径
                        .requestMatchers(
                                "/swagger-ui/**",     // Swagger UI 页面
                                "/v3/api-docs/**",    // OpenAPI JSON 文档
                                "/swagger-resources/**",
                                "/webjars/**",
                                "/docs/**"
                        ).permitAll()         // 允DEV访问
                        .requestMatchers(HttpMethod.OPTIONS).permitAll()
                        // 需要认证的接口路径（根据实际需求调整）
                        .requestMatchers("/api/**").authenticated()

                        .anyRequest().permitAll() // 其他路径允许匿名访问
                )
                .httpBasic(); // 启用基础认证

        return http.build();
    }

    /**
     * 自定义用户认证
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}